<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/17
 * Time: 10:26
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\common\model\app\Banner;
use app\common\utils\OssUtil;
use think\Db;

class Banners extends AdminController
{
    /**
     * @return \app\admin\model\PageResponse
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['limit', 'require',],
            ['offset', 'require',],
        ]);

        $page = Banner::manageList(intval($form['limit']),
            intval($form['offset']), intval($form['page_code'] ?? 0));
        return $page;
    }

    /**
     * @return ApiResponse
     */
    public function save() {
        Db::transaction(function(){
            $form = $this->getAndCheckForm([
                ['page', 'require',],
                ['image', 'require',],
                ['link_type', 'require|integer',],
            ]);

            $id = intval($form['id'] ?? 0);
            if ($id > 0) {
                $banner = Banner::get($id);
                OssUtil::delete($banner->image);
                Banner::update($form, [], Banner::getSaveFields());
            } else {
                Banner::create($form, Banner::getSaveFields());
            }
        });
        return ApiResponse::success();
    }

    /**
     * @return ApiResponse
     */
    public function del() {
        $form = $this->getAndCheckForm([
            ['id', 'require',],
        ]);
        $id = intval($form['id']);
        if ($id > 0){
            $banner = Banner::get($id);
            OssUtil::delete($banner->image);
            Banner::destroy(['id'=>$id]);
        }

        return ApiResponse::success();
    }

    /**
     * @param $ranks
     * @return ApiResponse
     */
    public function set_rank($ranks) {
        $ranks = json_decode($ranks, true);
        $list = [];
        foreach ($ranks as $rank) {
            $list[] = [
                'id' => $rank['id'],
                'rank' => $rank['rank'],
            ];
        }
        if (count($list) > 0) {
            (new Banner())->saveAll($ranks);
        }
        return ApiResponse::success();
    }

}